package com.yhk.wuchat.common.common.config;

import com.yhk.wuchat.common.common.thread.MyThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Spring自带线程池的配置类
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
    /**
     * 项目共用线程池
     */
    public static final String WUCHAT_EXECUTOR = "wuchatExecutor";

    /**
     * websocket通信线程池
     */
    public static final String WS_EXECUTOR = "websocketExecutor";

    @Override
    public Executor getAsyncExecutor() {
        return wuchatExecutor();
    }

    /**
     * 设置线程池参数
     * @return
     */
    //指定beanName
    @Bean(WUCHAT_EXECUTOR)
    @Primary
    public ThreadPoolTaskExecutor wuchatExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setWaitForTasksToCompleteOnShutdown(true);//优雅停机
        executor.setCorePoolSize(10);//核心线程数
        executor.setMaxPoolSize(10);//最大线程数
        executor.setQueueCapacity(200);//队列容量
        executor.setThreadNamePrefix("wuchat-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//满了调用线程执行，认为重要任务
        executor.setThreadFactory(new MyThreadFactory(executor));//装饰器模式
        executor.initialize();
        return executor;
    }

    @Bean(WS_EXECUTOR)
    @Primary
    public ThreadPoolTaskExecutor websocketExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setWaitForTasksToCompleteOnShutdown(true);//优雅停机
        executor.setCorePoolSize(16);//核心线程数
        executor.setMaxPoolSize(16);//最大线程数
        executor.setQueueCapacity(200);//队列容量
        executor.setThreadNamePrefix("websocket-executor-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());//满了直接丢弃
        executor.setThreadFactory(new MyThreadFactory(executor));//装饰器模式
        executor.initialize();
        return executor;
    }
}